package com.hc.category3;

import com.hc.common.utils.JsonUtil;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Category3Demo1 {

    @Test
    public void fun() {
        List<Category> categoryList = DB.init();
        //保存最终的结果
        List<Category> res = new ArrayList<>();

        for (Category category : categoryList) {
            //一级类别
            if (category.getPid() == null) {
                res.add(category);
            }
        }
        //遍历所有的一级类别，求它的子类别
        for (Category item : res) {
            item.setChildren(getChildren(item, categoryList));
        }

        Collections.sort(res, Comparator.comparingInt(Category::getSort));
        System.out.println(JsonUtil.obj2String(res));
    }

    /**
     * 递归：求参数category在list中所有的子类别
     *
     * @param category
     * @param list
     * @return
     */
    private List<Category> getChildren(Category category, List<Category> list) {
        //子类别
        List<Category> childList = new ArrayList<>();

        //遍历list求出category的子类别
        for (Category item : list) {
            if (category.getId().equals(item.getPid())) {
                childList.add(item);
            }
        }
        for (Category item : childList) {
            item.setChildren(getChildren(item, list));
        }
        Collections.sort(childList, Comparator.comparingInt(Category::getSort));
        return childList;
    }


}
